local EventMgr = class("EventMgr")

function EventMgr:ctor()
	--1
	self:initEventMgr()
end

--枚举事件名
function EventMgr:setEventTypes(types)
	self.TYPE = types
end

--需要每帧更新事件的对象
function EventMgr:addObjToFrameUpdate(obj,listeners)
	if not self.FrameTable then
		local temp = {}
		setmetatable(temp, {__mode = "k"})
		self.FrameTable = temp
	end
	if not self.FrameTable[obj] then
		--只绑定一个函数
		self.FrameTable[obj] = listeners
	end
end

function EventMgr:removeFromUpdate(obj)
    if self.FrameTable then
        self.FrameTable[obj] = nil
    end
end

function EventMgr:updateFrame(...)
	if not self.FrameTable then return end

	for key,listener in pairs(self.FrameTable) do
		if key then	
			listener(key,...)
		end	
	end
end

--注册全局事件EM管理
function EventMgr:addEmHandle(handle)
    self._emHandles[#self._emHandles+1] = handle
end

--设置事件管理器
function EventMgr:initEventMgr()
    self.listeners_ = {}
    self.nextListenerHandleIndex_ = 0
    self._emHandles = {}
end

function EventMgr:addEventListener(eventName, listener)
    assert(type(eventName) == "string" and eventName ~= "",
        "EventMgr:addEventListener() - invalid eventName")

    if self.listeners_[eventName] == nil then
        self.listeners_[eventName] = {}
    end

    self.nextListenerHandleIndex_ = self.nextListenerHandleIndex_ + 1
    local handle = tostring(self.nextListenerHandleIndex_)
    self.listeners_[eventName][handle] = listener
    return handle
end

function EventMgr:dispatchEvent(name,...)
    local eventName = name

    if self.listeners_[eventName] == nil then return end

    local currentListeners = self.listeners_[eventName]
    local result = nil
    for handle, listener in pairs(currentListeners) do
    	result = listener(...)
    end
    return result
end

function EventMgr:removeEvent(eventName)
    for _eventName, listenersForEvent in pairs(self.listeners_) do
        if _eventName == eventName then
            for handle, _ in pairs(listenersForEvent) do
                listenersForEvent[handle] = nil
            end
        end
    end
end

function EventMgr:clear()
    local listeners = self.listeners_
	for eventName, listenersForEvent in pairs(listeners) do
        for handle, _ in pairs(listenersForEvent) do
            listenersForEvent[handle] = nil
        end
    end

     if self.FrameTable then
        -- local frameTable = self.FrameTable
        -- for k,_ in pairs(frameTable) do
        --     frameTable[k] = nil
        -- end
        self.FrameTable = nil
    end

    local handles = self._emHandles
    for k,v in pairs(handles) do
        EM:remove(v)
    end
end

return EventMgr